<template>
  <!-- 搜索工作栏 -->
    <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <template v-for="(item, index) in visibleSearchConfig" :key="index">
        <el-form-item :prop="item.prop">
          <component
            :is="
              item.type === 'dateRange'
                ? 'el-date-picker'
                : item.type === 'select'
                ? 'el-select'
                : 'el-input'
            "
            v-model="queryParams[item.prop]"
            :placeholder="item.placeholder"
            :start-placeholder="item.startPlaceholder"
            :end-placeholder="item.endPlaceholder"
            :type="item.type === 'dateRange' ? 'daterange' : 'text'"
            :value-format="item.type === 'dateRange' ? 'YYYY-MM-DD HH:mm:ss' : undefined"
            :default-time="
              item.type === 'dateRange'
                ? [new Date('1 00:00:00'), new Date('1 23:59:59')]
                : undefined
            "
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          >
            <template v-if="item.type === 'select'">
              <el-option
                v-for="opt in item.options"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </template>
          </component>
        </el-form-item>
      </template>

      <el-form-item>
        <el-button @click="handleQuery"> <Icon icon="ep:search" class="mr-5px" /> 搜索 </el-button>
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" class="mr-5px" /> 重置 </el-button>
      </el-form-item>
      <div class="flex justify-center w-full">
        <el-button type="text" @click="toggleExpand" class="expand-toggle-button">
          {{ isExpanded ? '收起' : '展开' }}
          <Icon :icon="isExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" class="ml-5px" />
        </el-button>
      </div>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-row :gutter="10" style="margin-bottom: 16px">
      <el-col :span="12">
        <div style="text-align: left">
          <el-button
            type="default"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['system:tenant:export']"
          >
            导出
          </el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="text-align: right">
          <el-button type="default" plain @click="btnLie">
            <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
            列表字段
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="list"  show-summary 
      :summary-method="getSummaries"
      :summary-props="{ columns: ['quantity', 'excludeTaxAmount', 'includeTaxAmount'] }">
      <!-- 序号列 -->
      <el-table-column label="序号" type="index" align="center" width="60" />

      <!-- 仓库相关列 -->
      <el-table-column label="出库仓库" v-if="visibleColumns.warehouseName" align="center" prop="warehouseName"/>
      <el-table-column label="库区" v-if="visibleColumns.area" align="center" prop="area"  />
      <el-table-column label="库位" v-if="visibleColumns.location" align="center" prop="location"  />

      <!-- 物料信息列 -->
      <el-table-column label="物料名称" v-if="visibleColumns.materialName" align="center" prop="materialName"  />
      <el-table-column label="物料编号" align="center" prop="materialCode" v-if="visibleColumns.materialCode"  />
      <el-table-column label="图片" align="center" prop="imageUrl" v-if="visibleColumns.imageUrl" >
        <template #default="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
            style="width: 70px; height: 70px"
            preview-teleported
            hide-on-click-modal
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="category" v-if="visibleColumns.category"  />
      <el-table-column label="规格" align="center" prop="spec"  v-if="visibleColumns.spec"   />
      <el-table-column label="型号" align="center" prop="model"  v-if="visibleColumns.model"  />

      <!-- 数量单位列 -->
      <el-table-column label="基本单位" align="center" prop="unit"  v-if="visibleColumns.unit"   />
      <el-table-column label="基本数量" align="center" prop="quantity"  v-if="visibleColumns.quantity" />

      <!-- 金额相关列 -->
      <el-table-column label="出库不含税金额" align="center" prop="excludeTaxAmount"  v-if="visibleColumns.excludeTaxAmount"  width="140"  />
      <el-table-column label="出库含税金额" align="center" prop="includeTaxAmount"  v-if="visibleColumns.includeTaxAmount"  />
    
      <el-table-column label="查看明细" align="center"  fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="openDetail(scope.row)"
            v-hasPermi="['pay:order:query']"
          >
            查看明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 自定义字段 -->
  <el-dialog
    v-model="dialogVisible"
    title="自定义字段"
    width="50%"
    :before-close="handleClose"
  >
    <div class="content">
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.warehouseName"  label="出库仓库" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.area"  label="库区" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.location"  label="库位" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.materialName"  label="物料名称" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.materialCode"  label="物料编号" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.imageUrl"  label="图片" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.category"  label="分类" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.spec"  label="规格" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.model"  label="型号" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.unit"  label="基本单位" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.quantity"  label="基本数量" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.excludeTaxAmount"  label="出库不含税金额" size="large" /></div>
      <div class="content-list"><el-checkbox v-model="tempVisibleColumns.includeTaxAmount"  label="出库含税金额" size="large" /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as RefundApi from '@/api/pay/refund'
import * as AppApi from '@/api/pay/app'
import download from '@/utils/download'
import type { TableColumnCtx } from 'element-plus'
import type { VNode } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
defineOptions({ name: 'PayRefund' })

const message = useMessage() // 消息弹窗

const loading = ref(false) // 列表遮罩层
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const visibleColumns =ref({
  warehouseName:true,
  area:true,
  location:true,
  materialName:true,
  materialCode:true,
  imageUrl:true,
  category:true,
  spec:true,
  model:true,
  unit:true,
  quantity:true,
  excludeTaxAmount:true,
  includeTaxAmount:true
})
const dialogVisible=ref(false)
const tempVisibleColumns = ref({...visibleColumns.value})

const btnLie = () => {
  tempVisibleColumns.value = {...visibleColumns.value}
  dialogVisible.value = true
}
const isExpanded = ref(false)
// 切换展开状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}
const searchConfig = ref([
  {
    prop: 'materialId',
    placeholder: '请输入物料名称/编号',
    type: 'input',
    showInCollapsed: true
  },
  {
    prop: 'materialKey',
    placeholder: '请输入物料分类',
    type: 'input',
    showInCollapsed: true
  },
  {
    prop: 'model',
    placeholder: '请输入库区名称',
    type: 'input',
    showInCollapsed: true
  },
  {
    prop: 'model',
    placeholder: '请输入仓亏名称',
    type: 'input',
    showInCollapsed: true
  },
  {
    prop: 'model',
    placeholder: '请输入型号',
    type: 'input',
    showInCollapsed: true
  },
  {
    prop: 'model',
    placeholder: '请输入规格',
    type: 'input',
    showInCollapsed: false
  },
  {
    prop: 'createTime',
    type: 'dateRange',
    startPlaceholder: '制单开始日期',
    endPlaceholder: '制单结束日期',
    showInCollapsed: false
  }
])
const generateMockData = () => {
  return [
    {
      id: 1,
      warehouseName: "北京中心仓",
      area: "A区",
      location: "A-101",
      materialName: "精密轴承",
      materialCode: "MAT-001",
      imageUrl: "https://example.com/bearing.jpg",
      category: "机械零件",
      spec: "6202ZZ",
      model: "P5级",
      unit: "个",
      quantity: 100,
      excludeTaxAmount: 15800, 
      includeTaxAmount: 18250 
    },
    {
      id: 2,
      warehouseName: "上海分仓",
      area: "C区",
      location: "C-305",
      materialName: "工业润滑油",
      materialCode: "MAT-002",
      imageUrl: "https://example.com/oil.jpg",
      category: "化工产品",
      spec: "ISO VG 46",
      model: "耐高温",
      unit: "桶",
      quantity: 50,
      excludeTaxAmount: 22500, 
      includeTaxAmount: 26325  
    }
  ];
};

// 所有模拟数据
const allMockData = ref(generateMockData());

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  
  try {
    // 使用setTimeout模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 在实际项目中这里应该是API返回的数据，现在我们用模拟数据
    list.value = allMockData.value;
    total.value = allMockData.value.length;
    
  } catch (error) {
    console.error('获取数据失败:', error);
    message.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 根据展开状态过滤显示的搜索项
const visibleSearchConfig = computed(() => {
  return searchConfig.value.filter((item) => isExpanded.value || item.showInCollapsed)
})
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantId: undefined,
  appId: undefined,
  channelCode: undefined,
  merchantOrderId: undefined,
  merchantRefundId: undefined,
  status: undefined,
  payPrice: undefined,
  refundPrice: undefined,
  channelOrderNo: undefined,
  channelRefundNo: undefined,
  createTime: [],
  successTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出等待
const appList = ref([]) // 支付应用列表集合
interface Product {
  quantity: number,
  excludeTaxAmount:number,
  includeTaxAmount:number
}
interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'none' } }, [
        '合计',
      ])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = ` ${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = ''
    }
  })

  return sums
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 查询列表 */
// const getList = async () => {
//   loading.value = true
//   try {
//     const data = await RefundApi.getRefundPage(queryParams)
//     list.value = data.list
//     total.value = data.total
//   } finally {
//     loading.value = false
//   }
// }
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
// 列表字段确认选择
const handleConfirm = () => {
  visibleColumns.value = { ...tempVisibleColumns.value }
  dialogVisible.value = false

  // 这里可以添加保存到本地存储的逻辑
  // localStorage.setItem('visibleColumns', JSON.stringify(visibleColumns.value))
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RefundApi.exportRefund(queryParams)
    download.excel(data, '物料出库汇总表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 预览详情 */
const openDetail = (row) => {
   router.push({
     path: `/erp/logistics/outboundDetails`, 
     params:row
    })
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  appList.value = await AppApi.getAppList()
})
</script>
<style scoped>
:deep(.el-table__footer-wrapper tfoot td) {
background-color: #fff3e0;
}
.expand-toggle-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  font-size: 12px;
  color: #909399;
}

/* 使表单行间距更合理 */
.el-form-item {
  margin-bottom: 10px;
}
.order-font {
  padding: 2px 0;
  font-size: 12px;
}
</style>
